package com.njy.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.njy.consumer.feign.Payment;
import com.njy.pojo.CommonResult;
import com.njy.pojo.Dept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class ConsumerController {
    @Autowired
    private Payment payment;


    @GetMapping("/consumer/feign/dept/get/{id}")
    @SentinelResource(value = "getDeptById",fallback = "fallbackMethod")
    public CommonResult<Dept> getDeptById(@PathVariable(value = "id")Long id){
        long start = System.currentTimeMillis();
        log.info("-----进入主业务逻辑-----");
        CommonResult<Dept> result = payment.getDeptById(id);
        log.info("-----返回结果-----{}",result.toString());
        if (id == 6) {
            log.error("-----主业务逻辑，抛出非法参数异常-----");
            log.error("-----非法参数异常-----调用时间{}-----",System.currentTimeMillis()-start);
            throw new IllegalArgumentException("IllegalArgumentException，非法参数异常....");
            //如果查到的记录也是 null 也控制正异常
        } else if (result.getData() == null) {
            log.error("-----主业务逻辑，抛出空指针异常-----");
            log.error("-----空指针异常-----调用时间{}-----",System.currentTimeMillis()-start);
            throw new NullPointerException("NullPointerException，该ID没有对应记录,空指针异常");
        }
        log.info("-----正常运行-----调用时间{}-----",System.currentTimeMillis()-start);
        return result;
    }
    //处理异常的回退方法（服务降级）
    public CommonResult<Dept> fallbackMethod(Long id, Throwable e){
        log.error("-----服务降级逻辑-----");
        Dept dept = new Dept(id, "null", "null");
        return new CommonResult(444, "服务被降级！异常信息为：" + e.getMessage(), dept);
    }
}
